package com.ruoyi.framework.interceptor;



import com.ruoyi.common.utils.UserTokenManager;
import com.ruoyi.common.utils.sign.Sign;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Map;


public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Long.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    // 解析token获取userId
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)){
            return null;
        }
        Map<String, Object> result = UserTokenManager.getUserId(token);
        return result.get(Sign.CLAIM_USER_ID);
    }
}
